package cn.pconline.autoclub.web.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.entity.Album;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.ClubPhoto;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.Photo;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.AlbumService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.app.AppControllerStatic;
import cn.pconline.autoclub.util.dyna.AbstractDyna;
import cn.pconline.autoclub.web.UserAuth;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * http://rdtrac.pc.com.cn/autoclub/wiki/appapi/4.0
 * app相册相关controller
 */
@Controller
@RequestMapping(value = "/appapi")
public class AppAlbumController {

	@Autowired
	private AlbumService albumService;
	
	@Autowired
	private ClubService clubService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private UserAuth userAuth;
	
	@Autowired
	private DynaService dynaService;
	@Autowired
	private MessageService messageService;
	
	private static final Logger log = LoggerFactory.getLogger(AppAlbumController.class);
   
    /**
     * 1.2.1 根据车友会ID,返回相册列表
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/album/getAlbumByClubId.do", method = RequestMethod.GET)
    public void getAlbumByClubId(HttpServletRequest request, HttpServletResponse response){
    	WebUtils.setEncoding4App(request, response);
    	int xssEncode = AppControllerStatic.paramXssEncode(request);
    	String callback = AppControllerStatic.paramCallback(request);
    	long clubId = AppControllerStatic.paramClubId(request);
    	int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
    	
    	JSONObject jsonObject = new JSONObject();
        JSONArray albumArray = new JSONArray();
    	//判断车友会是否合法
    	Club club =clubService.getValidClub(clubId);
        if (club == null) {
            AppControllerStatic.printErrorMsg(response, "该车友会ID不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        Pager<Album> pager = albumService.pagerAllAlbumByClubId(clubId, pageSize, pageNo);
        albumService.loadPhotoByAlbumsLimit(pager.getResultList(), 5);
        if (pager != null && !pager.getResultList().isEmpty()) {
            for (Album album : pager.getResultList()) {
            	JSONObject albumJson = new JSONObject();
        		albumJson.put("albumId", album.getAlbumId());
        		albumJson.put("albumName", xssEncode == 0 ? album.getName() :EncodeUtils.encodeForHTMLFilterNull(album.getName()));
        		albumJson.put("coverUrlSmall", album.getCover294x294());
        		albumJson.put("createAt", album.getCreateAt());
        		albumJson.put("createBy", album.getCreateBy());
        		long createBy = album.getCreateBy();
        		if(createBy>0){
        			albumJson.put("nickName", xssEncode == 0 ? userService.getNickNameByUserId(createBy):EncodeUtils.encodeForHTMLFilterNull(userService.getNickNameByUserId(createBy)));
            		User createUser = userService.findUser(album.getCreateBy()); //创建用户
            		if(createUser!=null){
            			albumJson.put("authorPhoto",createUser.getAvatar50());
                		albumJson.put("isVip", createUser.getVip());
            		}
        		}
        		albumJson.put("photoSize", album.getQuantity());
        		JSONArray photoArray = new JSONArray();
        		//最多只返回4张照片
        		if(album.getPhotos()!=null) {
                                int flag = 0;
        			for(Photo photo:album.getPhotos()) {
                                    if(flag==0){
                                        flag=1;//不包括最新上传的那一张
                                        continue;
                                    }
                                    JSONObject photoJson = new JSONObject();
                                    photoJson.put("photoId",photo.getPhotoId());
                                    photoJson.put("urlSmall",photo.getUrl144x144());
                                    photoJson.put("urlBig", photo.getUrl700x());
                                    photoArray.add(photoJson);
        			}
        		}
        		
        		albumJson.put("photoList", photoArray);
        		albumArray.add(albumJson);
            }
        }
        
        jsonObject.put("clubId",clubId);
        jsonObject.put("clubName", xssEncode == 0 ? club.getName():EncodeUtils.encodeForHTMLFilterNull(club.getName()));
        jsonObject.put("albumList", albumArray);
        AppControllerStatic.printSuccessMsgPager(response, jsonObject, callback, pager, AppControllerStatic.V1_VERSION_LATEST);
        
    }
    
    /**
     * 根据相册ID返回相片列表
     * @param request
     * @param response
     */
    @RequestMapping(value="/1.0/album/getPhotoByAlbumId.do", method=RequestMethod.GET)
    public void getPhotoByAlbumId(HttpServletRequest request, HttpServletResponse response) {
    	//获取相关参数
    	WebUtils.setEncoding4App(request, response);
        String callback = AppControllerStatic.paramCallback(request);
        long albumId = AppControllerStatic.paramAlbumId(request);
    	int xssEncode = AppControllerStatic.paramXssEncode(request);
    	int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
    	
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        
        //判断相册是否存在
       Album album = albumService.getAlbumById(albumId);
       if(album == null) {
        	AppControllerStatic.printErrorMsg(response, "该相册不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
       
       if(album.getStatus() == Album.STATUS_DELETE) {
    	   AppControllerStatic.printErrorMsg(response, "该相册已被删除", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
    	   return;
       }
        //获得创建相册者的资料
        User user = userService.findUser(album.getCreateBy());
        jsonObject.put("albumId" , album.getAlbumId());
        jsonObject.put("isDefault" , album.getIsDefault());
        jsonObject.put("albumName", xssEncode == 0 ? album.getName() : EncodeUtils.encodeForHTMLFilterNull(album.getName()));
        jsonObject.put("createAt", album.getCreateAt());
        jsonObject.put("createBy", album.getCreateBy());
        jsonObject.put("nickName", user == null ? "" : (xssEncode == 0 ? user.getNickname() : EncodeUtils.encodeForHTMLFilterNull(user.getNickname())));
        jsonObject.put("authorPhoto",  user == null ? "" :  user.getAvatar50());
        jsonObject.put("isVip",  user == null ? "" : user.getVip() );
        jsonObject.put("clubId", album.getClubId());
        
        //获取相册相片列表
        Pager<Photo> pager = albumService.pagerAllPhotosByAlbumId(albumId, pageSize, pageNo);
        if (pager != null && !pager.getResultList().isEmpty()) {
            for (Photo photo : pager.getResultList()) {
            	JSONObject json = new JSONObject();
            	json.put("photoId", photo.getPhotoId());
            	json.put("createBy",photo.getCreateBy());
            	json.put("urlSmall",photo.getUrl144x144());
            	json.put("urlBig", photo.getUrl700x());
            	jsonArray.add(json);
            }
        }
        
        jsonObject.put("photoList", jsonArray);
        
        AppControllerStatic.printSuccessMsgPager(response, jsonObject, callback, pager, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 1.3.0 获取车友会最新照片列表
     * @param request
     * @param response
     */
    @RequestMapping(value="/1.0/album/getLatestPhotosByClubId.do", method=RequestMethod.GET)
    public void getLatestPhotosByClubId(HttpServletRequest request, HttpServletResponse response){
    	//获取相关参数
    	WebUtils.setEncoding4App(request, response);
    	String callback = AppControllerStatic.paramCallback(request);
    	long clubId = AppControllerStatic.paramClubId(request);
    	int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
    	JSONObject jsonObject = new JSONObject();
    	JSONArray jsonArray = new JSONArray();
    	//判断车友会是否合法
    	Club club =clubService.getValidClub(clubId);
        if (club == null) {
            AppControllerStatic.printErrorMsg(response, "该车友会ID不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        jsonObject.put("clubId",clubId);
        //TODO性能优化： 这里的相片可以考虑批量查出来，然后最新的相片列表可以放到MC里面。key为：getLatestPhotosByClubId-clubId
        //这样的话，相片的增删移就要记得清下缓存
        //TODO 相片相关的KEY可以找一个地方放在一起，统一管理
        Pager<Photo> pager = albumService.getPhotosOrderDesc(clubId, pageNo, pageSize );
        if (pager != null && !pager.getResultList().isEmpty()) {
        	for(Photo photo : pager.getResultList()){
        		JSONObject json = photo.toJson();
        		json.put("urlSmall", photo.getUrl144x144());
        		json.put("urlBig", photo.getUrl700x());
        		jsonArray.add(json);
        	}
        }
        
        jsonObject.put("photoList", jsonArray);
        AppControllerStatic.printSuccessMsgPager(response,jsonObject, callback, pager,AppControllerStatic.V1_VERSION_LATEST);
    }
    
    @RequestMapping(value = "/1.0/album/editAlbum.do", method = RequestMethod.POST)
    public void editAlbum(HttpServletRequest request, HttpServletResponse response){
        //获取相关参数
        WebUtils.setEncoding4App(request, response);
        
        long albumId = AppControllerStatic.paramAlbumId(request);
        
        JSONObject jsonObject = new JSONObject();
        
        User user = userAuth.getUser(request, response);
        if(user == null || user.getUid() == User.ANONYMOUS.getUid()) {
            AppControllerStatic.printErrorMsg(response, "用户没登录", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        ClubMember member = memberService.findClubMemberByUserId(user.getUid());
        if(member == null) {
            AppControllerStatic.printErrorMsg(response, "用户没加入车友会" ,jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        String albumName = WebUtils.param(request, "albumName", null);
        if (StringUtils.isBlank(albumName)) {
            AppControllerStatic.printErrorMsg(response, "相册名称不能为空" ,jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        } else if (!albumName.matches(Regex.chineseNumAbc.value)) {
            AppControllerStatic.printErrorMsg(response, "请输入汉字、数字或者字母" ,jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        } else if (albumName.length() > 20) {
            AppControllerStatic.printErrorMsg(response, "请使用长度为1～20个字符的数字、字母或者汉字" ,jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        Album album = null;
        Date now = new Date();
        if (albumId == 0) { // 新增
            album = new Album();
            album.setClubId(member.getClubId());
            album.setCover("http://www1.pcauto.com.cn/bbs/cargroup/2014/images/defaultphoto.png");
            album.setCreateBy(user.getUid());
            album.setCreateAt(now);
        } else { // 更新
            album = albumService.getValidAlbum(albumId);
            if (album == null) {
                AppControllerStatic.printErrorMsg(response, "相册不存在" ,jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
                return;
            }
            
            long userId = user.getUid();
            boolean hasRole = false;
            if(userId == album.getCreateBy()){ // 创建者
            	hasRole = true;
            }else{//是否为管理员
            	long clubId = album.getClubId();
            	hasRole = memberService.isClubNormalAdmin(userId, clubId);
            }
            if(!hasRole) {
            	AppControllerStatic.printErrorMsg(response, "您不是会长或该相册创建者!" ,jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
            	return;
            }
        }
        album.setName(albumName);
        album.setUpdateAt(now);

        boolean success = true;
        try {
            albumService.updateOrSave(album);
        } catch (DuplicateKeyException ex) {
            success = false;
        } catch (Exception e) {
            success = false;
        }
        if(success) {
            String message = null;
            if(albumId > 0) {
                message = "修改成功";
            } else {
                message = "创建成功";
            }
            jsonObject.put("albumId", album.getAlbumId());
            AppControllerStatic.printSuccessMsg(response, message, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
        } else {
            AppControllerStatic.printErrorMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
        }
    }
    
    @RequestMapping(value = "/1.0/album/uploadPhotos.do", method = RequestMethod.POST)
    public void uploadPhotos(HttpServletRequest request, HttpServletResponse response){
        //获取相关参数
        WebUtils.setEncoding4App(request, response);
        
        long albumId = AppControllerStatic.paramAlbumId(request);
        
        Album album = albumService.getAlbumById(albumId);
        if(album == null) {
            AppControllerStatic.printErrorMsg(response, "相册不存在" ,null, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        User user = userAuth.getUser(request, response);
        if(user == null || user.getUid() == User.ANONYMOUS.getUid()) {
            AppControllerStatic.printErrorMsg(response, "用户没登录", null , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        ClubMember member = memberService.findClubMemberByUserId(user.getUid());
        if(album.getClubId() != member.getClubId()) {
        	AppControllerStatic.printErrorMsg(response, "不是该车友会会员，无权操作!" ,null, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        JSONArray photos = WebUtils.parseArray(request, "photoList");
        if(photos == null) {
            AppControllerStatic.printErrorMsg(response, "请先上传图片!" ,null, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        try {
            String cover = "";
            List<Photo> list = new ArrayList<Photo>();
            for (int i = 0; i < photos.size(); i++) {
                JSONObject o = photos.getJSONObject(i);
                String url = o.getString("url");
                if(!url.endsWith(".jpg")) { //如果不是.jpg后缀的图片则不保存
                    continue;
                }
                if (i == photos.size() - 1) {
                    cover = url;
                }
                Photo photo = new Photo();
                photo.setName(o.getString("name"));
                photo.setUrl(o.getString("url"));
                photo.setAlbumId(albumId);
                photo.setCreateBy(user.getUid());
                photo.setWidth(o.getInteger("width"));
                photo.setHeight(o.getInteger("height"));
                list.add(photo);
            }
            long[] ids = albumService.batchCreatePhotos(albumId, list);
            
            //成功生成车友会最新上传相片
            if (ids.length > 0) {
                List<ClubPhoto> clubPhotos = new ArrayList<ClubPhoto>(ids.length);
                for (long id : ids) {
                    ClubPhoto clubPhoto = new ClubPhoto();
                    clubPhoto.setAlbumId(albumId);
                    clubPhoto.setClubId(member.getClubId());
                    clubPhoto.setPhotoId(id);
                    clubPhoto.setCreateAt(new Date());
                    clubPhoto.setCreateBy(user.getUid());
                    clubPhoto.setStatus(ClubPhoto.STATUS_NORMAL);
                    clubPhotos.add(clubPhoto);
                }
                albumService.batchCreateClubPhoto(member.getClubId(), clubPhotos);
            }
            
            synchronized (album) {
                albumService.refshAlbumPhotos(albumId, cover);
            }
            
            //创建图片动态
            List<DynaImage> dynaImages = new ArrayList<DynaImage>();
            int imgSize = photos.size();
            for (int i = 0; i < imgSize; i++) {
                JSONObject o = JSONObject.parseObject(photos.getString(i));
                DynaImage dynaImage = new DynaImage();
                dynaImage.setSeq(i + 1);// 车友会的图片的seq跟论坛的图片的seq都统一从1开始
                dynaImage.setUrl(o.getString("url"));
                dynaImage.setWidth(o.getInteger("width"));
                dynaImage.setHeight(o.getInteger("height"));
                dynaImages.add(dynaImage);
            }
            
            Date cur = DateUtils.getNow();
            AbstractDyna dyna = new AbstractDyna();
            dyna.setClubId(member.getClubId());
            dyna.setContent("{pictureNum:" + imgSize + "}");
            dyna.setCreateBy(user.getUid());
            dyna.setCreateName(user.getNickname() != null ? user.getNickname() : user.getUsername());
            dyna.setCreateDate(cur);
            dyna.setTargetId(albumId);
            dynaService.createPictureDyna(dyna, dynaImages);
        } catch (Exception e) {
            log.error("post picDyna --uploadPhotos!", e);
            AppControllerStatic.printErrorMsg(response, null, null, AppControllerStatic.V1_VERSION_LATEST);
        }
        AppControllerStatic.printSuccessMsg(response, "上传相片成功" ,null, null, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    @RequestMapping(value = "/1.0/album/setAlbumCover.do", method = RequestMethod.POST)
    public void setAlbumCover(HttpServletRequest request, HttpServletResponse response){
        //获取相关参数
        WebUtils.setEncoding4App(request, response);
        
        long albumId = AppControllerStatic.paramAlbumId(request);
        long photoId = AppControllerStatic.paramPhotoId(request);
        
        User user = userAuth.getUser(request, response);
        if(user == null || user.getUid() == User.ANONYMOUS.getUid()) {
            AppControllerStatic.printErrorMsg(response, "用户没登录", null , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        Photo photo = albumService.getPhotoById(photoId, albumId);
        if(photo == null) {
        	 AppControllerStatic.printErrorMsg(response, "照片不存在", null , null, AppControllerStatic.V1_VERSION_LATEST);
             return;
        }
        
        String newCoverUrl = photo.getUrl();
        
        if(StringUtils.isBlank(newCoverUrl)) {
            AppControllerStatic.printErrorMsg(response, "请先上传封面" ,null, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }

        Album album = albumService.getAlbumById(albumId);
        if(album == null) {
            AppControllerStatic.printErrorMsg(response, "相册不存在" ,null, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        if(newCoverUrl.equals(album.getCover())) {
            AppControllerStatic.printSuccessMsg(response, "设置封面完成" ,null, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        long userId = user.getUid();
        boolean hasDeleteRole = false;
        if(userId == album.getCreateBy()){ // 创建者
        	hasDeleteRole = true;
        }else{//是否为管理员
        	long clubId = album.getClubId();
        	hasDeleteRole = memberService.isClubNormalAdmin(userId, clubId);
        }
        if(!hasDeleteRole) {
        	AppControllerStatic.printErrorMsg(response, "您不是会长或该相册创建者!", null, null, AppControllerStatic.V1_VERSION_LATEST);
        	return;
        }
        
        albumService.setAlbumCover(album, newCoverUrl);
        AppControllerStatic.printSuccessMsg(response, "设置封面成功" ,null, null, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 创建者|会长|副会长都可以删除
     * 
     * 删除照片（批量）
     */
    @RequestMapping(value = "/1.0/album/delPhotos.do", method = RequestMethod.POST)
    public void delPhotos(HttpServletRequest request, HttpServletResponse response){
        WebUtils.setEncoding4App(request, response);
        long albumId = AppControllerStatic.paramAlbumId(request);
        Album album = albumService.getAlbumById(albumId);
        if(album == null) {
            AppControllerStatic.printErrorMsg(response, "相册不存在" ,null, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        User user = userAuth.getUser(request, response);
        if(user == null || user.getUid() == User.ANONYMOUS.getUid()) {
            AppControllerStatic.printErrorMsg(response, "用户没登录", null , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        long clubId = album.getClubId();//创建者可能先退出了车友会
        String photoIds = WebUtils.param(request, "photoIds", "");
        String[] array = photoIds.split(",");
        int size = array.length;
        List<Photo> photos = new ArrayList<Photo>(size);
        List<ClubPhoto> clubPhotos = new ArrayList<ClubPhoto>(size);
        try {
            for (String s : array) {
                long photoId = Long.parseLong(s);
                Photo photo = albumService.getValidPhoto(photoId, albumId);
                //照片已经不存在，或已被删除，不操作
                if(photo == null) {
                	continue;
                }
                //会长，照片发布者可以删除操作
                if(!albumOperateAuth(photo.getCreateBy(), clubId, user.getUid())) {
                	AppControllerStatic.printErrorMsg(response, "您没有操作权限!", null, null, AppControllerStatic.V1_VERSION_LATEST);
                    return;
                }
                photo.setStatus(Photo.STATUS_DELETE);
                photos.add(photo);

                ClubPhoto clubPhoto = new ClubPhoto();
                clubPhoto.setAlbumId(albumId);
                clubPhoto.setClubId(clubId);
                clubPhoto.setStatus(ClubPhoto.STATUS_DELETE);
                clubPhoto.setPhotoId(photoId);
                clubPhotos.add(clubPhoto);
            }
            if (size != 0) {
                // 同个事务中更新图片
                albumService.updatePhotos(photos);
                //同个事物中删除车友会图片
                albumService.deleteClubPhotos(clubPhotos);
                // 更新相册的图片数量
                albumService.refshAlbumPhotos(albumId, "");
            }
        }catch (Exception e) {
            AppControllerStatic.printErrorMsg(response, "出错了!", null, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        AppControllerStatic.printSuccessMsg(response,null, null,AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 1.2.6 删除相册
     * @param request
     * @param response
     */
    @RequestMapping(value="/1.0/album/delAlbum.do", method=RequestMethod.POST)
    public void delAlbum(HttpServletRequest request, HttpServletResponse response){
    	//获取相关参数
    	WebUtils.setEncoding4App(request, response);
        String callback = AppControllerStatic.paramCallback(request);
        long albumId = AppControllerStatic.paramAlbumId(request);
        JSONObject jsonObject = new JSONObject();
        //获取用户信息
        User user = userAuth.getUser(request, response);
        //判断用户是否登录
        if (user == null || user.getUid() <= 0) {
            AppControllerStatic.printErrorMsg(response, "用户未登录", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        Album album = albumService.getValidAlbum(albumId);
        if (albumId < 1 || album == null) {
        	AppControllerStatic.printErrorMsg(response, "数据异常,该相册不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        ClubMember member = memberService.findClubMemberByUserId(user.getUid());
        if(member==null){
        	AppControllerStatic.printErrorMsg(response, "用户没有加入车友会", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        long clubId = member.getClubId();
        if(album.getClubId()!=clubId){
        	AppControllerStatic.printErrorMsg(response, "您不是该车友会用户，无权操作", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        if(album.getIsDefault() == Album.ISDEFAULT_YES){
        	AppControllerStatic.printErrorMsg(response, "默认相册不能删除", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        if (!albumOperateAuth(album.getCreateBy(), clubId, user.getUid())){
        	AppControllerStatic.printErrorMsg(response, "您不是会长或该相册创建者", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        try {
            List<Photo> photos = albumService.getAllPhotosByAlbumId(albumId);
            List<ClubPhoto> clubPhotos = new ArrayList<ClubPhoto>(photos.size());
            for (Photo photo : photos) {
                photo.setUpdateAt(DateUtils.getNow());
                photo.setStatus(Photo.STATUS_DELETE);
                albumService.updatePhoto(photo);

                ClubPhoto clubPhoto = new ClubPhoto();
                clubPhoto.setAlbumId(photo.getAlbumId());
                clubPhoto.setClubId(clubId);
                clubPhoto.setStatus(ClubPhoto.STATUS_DELETE);
                clubPhoto.setPhotoId(photo.getPhotoId());
                clubPhotos.add(clubPhoto);
            }
            album.setStatus(Album.STATUS_DELETE);
            albumService.update(album,"status");
            albumService.deleteClubPhotos(clubPhotos);

            //某相册被会长删除，通知相册创建者
            if(memberService.isClubNormalAdmin(user.getUid(), clubId) && user.getUid() != album.getCreateBy()) {//会长删除相册
                User receiver = userService.findUser(album.getCreateBy());
                messageService.send(receiver, MessageService.DELETE_ALBUM,
                            album.getName(), messageService.assembleUserUrl(user.getUid(), user.getNickname()));
            }
        }catch (Exception e) {
        	AppControllerStatic.printErrorMsg(response, "出错了!", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
		}
        AppControllerStatic.printSuccessMsg(response,jsonObject, callback,AppControllerStatic.V1_VERSION_LATEST);
        
    }
    
    /**
     * 判断是否有权限
     * @param creatorId
     * @param clubId
     * @param operatorId
     * @return
     */
    private boolean albumOperateAuth(long creatorId, long clubId, long operatorId) {
        boolean result = false;
        if (memberService.isClubNormalAdmin(operatorId, clubId)) {
            result = true;
        } else {
            if (operatorId > 0) {
                if (creatorId == operatorId) {
                    result = true;
                }
            }
        }
        return result;
    }
    
    @RequestMapping(value = "/1.0/album/getAlbumByUserId.do")
    public void getAlbumByUserId(HttpServletRequest request, HttpServletResponse response){
        //获取相关参数
        WebUtils.setEncoding4App(request, response);
        int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
        //获取用户信息
        User user = userAuth.getUser(request, response);
        //判断用户是否登录
        if (user == null || user.getUid() <= 0) {
            AppControllerStatic.printErrorMsg(response, "用户未登录", null, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        ClubMember member = memberService.findClubMemberByUserId(user.getUid());
        if(member == null) {
            AppControllerStatic.printErrorMsg(response, "用户没加入车友会" ,null, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        JSONObject jsonObject = new JSONObject();
        Pager<Album> pager = albumService.getUserAlbum(user.getUid(), pageNo, pageSize);
        jsonObject.put("userId", user.getUid());
        jsonObject.put("clubId", member.getClubId());
        JSONArray albumList = new JSONArray();
        for(Album album : pager.getResultList()) {
            JSONObject albumJson = new JSONObject();
            albumJson.put("albumId", album.getAlbumId());
            albumJson.put("albumName", album.getName());
            albumJson.put("coverUrl", album.getCover());
            albumJson.put("isDefault", album.getIsDefault());
            albumList.add(albumJson);
        }
        jsonObject.put("albumList", albumList);
        
        AppControllerStatic.printSuccessMsgPager(response, jsonObject, null, pager, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 1.2.4 移动照片（批量）
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/album/movePhotos.do", method = RequestMethod.POST)
    public void movePhotos(HttpServletRequest request, HttpServletResponse response){
    	 //获取相关参数
        WebUtils.setEncoding4App(request, response);
        JSONObject jsonObject = new JSONObject();
        String callback = AppControllerStatic.paramCallback(request);
        long albumTargetId = WebUtils.paramLong(request, "albumIdMoveIn", 0);
        long albumSourceId = WebUtils.paramLong(request, "albumIdMoveOut", 0);
        if(albumTargetId==albumSourceId){
        	AppControllerStatic.printErrorMsg(response, "源相册与目标相册相同", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        Album sourceAlbum = albumService.getValidAlbum(albumSourceId);
        Album targetAlbum = albumService.getValidAlbum(albumTargetId);
        if (albumSourceId < 1 || albumTargetId < 1 || targetAlbum == null || sourceAlbum == null){
        	AppControllerStatic.printErrorMsg(response, "相册不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        if(sourceAlbum.getClubId()!=targetAlbum.getClubId()){
        	AppControllerStatic.printErrorMsg(response, "移动失败，源相册与目标相册不在同一个车友会", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        //获取用户信息
        User user = userAuth.getUser(request, response);
        //判断用户是否登录
        if (user == null || user.getUid() <= 0) {
            AppControllerStatic.printErrorMsg(response, "用户未登录", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        ClubMember member = memberService.findClubMemberByUserId(user.getUid());
        if(member==null){
        	AppControllerStatic.printErrorMsg(response, "用户没有加入车友会", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        long clubId = member.getClubId();
        if(clubId!=sourceAlbum.getClubId()){
        	AppControllerStatic.printErrorMsg(response, "您不是该车友会用户，无权操作", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        if (!albumOperateAuth(sourceAlbum.getCreateBy(), clubId, user.getUid())){
        	AppControllerStatic.printErrorMsg(response, "您不是会长或该相册创建者", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        Date date = DateUtils.getNow();
        long photoId;
        String photoIds = WebUtils.param( request, "photoIds", "");
        String[] array = photoIds.split(",");
        String message = "";
        boolean isMoveCover = false; // 是否作为封面的图片被移走
        int size = array.length;
        List<Photo> photos = new ArrayList<Photo>(size);
        for (String s : array) {
            photoId = Long.parseLong(s);
            Photo photo = albumService.getValidPhoto(photoId, albumSourceId);
            if (photo == null) {
            	AppControllerStatic.printErrorMsg(response, "数据异常, 图片不存在", jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
                return;
            }

            if (!albumOperateAuth(photo.getCreateBy(), clubId, user.getUid())) { // 不是图片上传者或会长
                message = "部分图片不是您上传的，无法移动!";
                size--;
                continue;
            }

            if (photo.getUrl().equals(sourceAlbum.getCover())) { // 作为封面的图片被移走
                isMoveCover = true;
            }

            photo.setUpdateAt(date);
            photos.add(photo);                       
        }
        if (size != 0) {
            //Album moveAlbum = albumService.getValidAlbum(moveAlbumId);
            if (moveAndDeletePhoto(photos, albumTargetId, targetAlbum.getClubId())) {
                message = "移动成功!" + message;

                int temp = sourceAlbum.getQuantity() - size;
                String albumCover = "http://www1.pcauto.com.cn/bbs/cargroup/2014/images/defaultphoto.png";
                if (isMoveCover) { // 作为封面的图片被移走
                    if (temp > 0) { // 设置为默认图片URL
                        List<Photo> li = albumService.listPhotosByAlbumId(sourceAlbum.getAlbumId(), 0, 1);
                        if(!li.isEmpty()){
                            albumCover = li.get(0).getUrl();
                        }
                    }
                } else {
                    albumCover = sourceAlbum.getCover();
                }
                // 更新移除图片的相册的图片数量
                albumService.refshAlbumPhotos(albumSourceId, albumCover);


                albumCover = photos.get(0).getUrl();
                // 更新移入图片的相册的图片数量
                albumService.refshAlbumPhotos(albumTargetId, albumCover);
               
            } else {
                message = "移动失败!" + message;
                AppControllerStatic.printErrorMsg(response, message, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
                return;
            }
        } else {
            message = "移动失败!" + message;
            AppControllerStatic.printErrorMsg(response, message, jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        AppControllerStatic.printSuccessMsg(response,message,jsonObject, callback,AppControllerStatic.V1_VERSION_LATEST);
        
        
    }
    
    /**
     * 移动照片，增加目标数据，删除原本数据
     */
    private boolean moveAndDeletePhoto(List<Photo> photos, long albumId, long clubId) {
        try {
            for (Photo photo : photos) {

                Photo newPhoto = new Photo();
                newPhoto.setPhotoId(photo.getPhotoId());
                newPhoto.setCreateAt(photo.getCreateAt());
                newPhoto.setCreateBy(photo.getCreateBy());
                newPhoto.setUpdateAt(DateUtils.getNow());
                newPhoto.setUrl(photo.getUrl());
                newPhoto.setStatus(photo.getStatus());
                newPhoto.setName(photo.getName());
                newPhoto.setAlbumId(albumId);
                if (albumService.getTableName(newPhoto).equals(albumService.getTableName(photo))) {
                    albumService.update(newPhoto);
                } else {
                    albumService.create(newPhoto);
                    albumService.deletePhoto(photo);
                }
                ClubPhoto newClubPhoto = albumService.getClubPhoto(clubId, photo.getAlbumId(), photo.getPhotoId());
                if (newClubPhoto != null) {
                    albumService.updateClubPhoto(clubId, photo.getAlbumId(), photo.getPhotoId(), albumId);
                }

            }

        } catch (Exception e) {
            log.error("moveAndDeletePhoto fail!", e);
            return false;
        }
        return true;
    }
}
